#include "ScriptMgr.h"
#include <luabind/luabind.hpp> 
#include <luabind/lua_include.hpp> 
#include <iostream>
#include "ExportFuncs.h"

using namespace std;

using std::string;

extern "C" 
{ 
#include "lua.h" 
#include "lauxlib.h" 
#include "lualib.h"
} 

#ifndef _DEBUG
#pragma comment(lib, "lua.lib")
#pragma comment(lib, "luabind.lib")
#else
#pragma comment(lib, "luaD.lib")
#pragma comment(lib, "luabindD.lib")
#endif


CScriptMgr::CScriptMgr()
{
	m_L = NULL;
}

CScriptMgr::~CScriptMgr()
{
	if (m_L)
	{
		lua_close(m_L);
		m_L = NULL;
	}
}

void CScriptMgr::Init()
{
	m_L = lua_open();
	if (!m_L)
	{
		exit(-1);
	}

	luaL_openlibs(m_L);
	luabind::open(m_L);

	ExportCFunc();

	LoadScript();

	//LoadLuaFunc();
}

void CScriptMgr::ExportCFunc()
{
	using namespace luabind;
	open(m_L);

	module(m_L)
	[
		def("GetMana", &GetMana)
		, def("GetPosX", &GetPosX)
		, def("GetPosY", &GetPosY)
		, def("GetLife", &GetLife)
		, def("MoveTo", &MoveTo)
		, def("BeDamage", &BeDamage)
		, def("IsAlive", &IsAlive)
		, def("Broadcast", &Broadcast)
		, def("CollectionCircle", &CollectionCircle)
		, def("CollectionLine", &CollectionLine)
		, def("GetTargetByIndex", &GetTargetByIndex)
		, def("MagicEnd", &MagicEnd)
		, def("SetMagicCDTime", &SetMagicCDTime)
		, def("SetNextStepTime", &SetNextStepTime)
	];
}


void CScriptMgr::LoadScript()
{
	if (luaL_dofile(m_L, "Test.lua"))
	{
		cout << "load Test.lua Error" << endl;
	}

	cout << "load Test.lua Success" << endl;
}

luabind::object CScriptMgr::GetMagicObj(unsigned int idLauncher)
{
	luabind::object magicFunctor = luabind::globals(m_L)["DoMagic"];
	return magicFunctor(idLauncher);
}
